package com.hillky.emos.wx.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hillky.emos.wx.domain.TbUser;
import com.hillky.emos.wx.exception.EmosException;
import com.hillky.emos.wx.mapper.TbDeptMapper;
import com.hillky.emos.wx.pojo.MessageEntity;
import com.hillky.emos.wx.service.TbUserService;
import com.hillky.emos.wx.mapper.TbUserMapper;
import com.hillky.emos.wx.task.MessageTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author Hillky
 * @description 针对表【tb_user(用户表)】的数据库操作Service实现
 * @createDate 2023-01-29 10:56:24
 */
@Service
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser>
        implements TbUserService {


    @Value("${wx.app-id}")
    private String appId;

    @Value("${wx.app-secret}")
    private String appSecret;

    @Autowired
    private TbUserMapper tbUserMapper;

    @Autowired
    private MessageTask messageTask;

    @Autowired
    private TbDeptMapper deptMapper;


    /**
     * 根据用户授权码获取微信openId
     * @param code
     * @return
     */
    public String getOpenId(String code){
        String url="https://api.weixin.qq.com/sns/jscode2session";
        HashMap map=new HashMap();
        map.put("appid", appId);
        map.put("secret", appSecret);
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String response= HttpUtil.post(url,map);
        JSONObject json= JSONUtil.parseObj(response);
        String openId=json.getStr("openid");
        if(openId==null||openId.length()==0){
            throw new RuntimeException("临时登陆凭证错误");
        }
        return openId;
    }


    /**
     * 根据openId查询用户
     * @param openId
     * @return
     */
    @Override
    public TbUser getByOpenId(String openId){
        LambdaQueryWrapper<TbUser> queryWrapper = new LambdaQueryWrapper<TbUser>().eq(TbUser::getOpenId, openId);
        TbUser tbUser = this.getOne(queryWrapper);
        return tbUser;
    }

    @Override
    public Integer insert(HashMap param) {
        return null;
    }



    @Override
    public Integer registerUser(String registerCode,String code, String nickName, String photo) {
        if(registerCode.equals("000000")){
            //注册超级管理员

            //查询是否存在超级管理员
            boolean rootFlag = tbUserMapper.haveRootUser();
            if(rootFlag){
                throw new EmosException("已存在超级管理员，无法继续注册");
            }
            TbUser tbUser = new TbUser();
            String openId = getOpenId(code);
            tbUser.setOpenId(openId);
            tbUser.setNickname(nickName);
            tbUser.setPhoto(photo);
            tbUser.setStatus(1);
            tbUser.setCreateTime(new Date());
            tbUser.setRoot(1);
            tbUser.setRole("[0]");
            this.save(tbUser);
            Integer id = tbUser.getId();

            //消息发送功能
            MessageEntity entity=new MessageEntity();
            entity.setSenderId(0);
            entity.setSenderName("系统消息");
            entity.setUuid(IdUtil.simpleUUID());
            entity.setMsg("欢迎您注册成为超级管理员，请及时更新你的员工个人信息。");
            entity.setSendTime(new Date());
            messageTask.sendAsync(id+"",entity);

            return id;
        }else{
            //注册普通用户
        }
        return 0;
    }

    @Override
    public Set<String> searchUserPermissions(Integer userId) {
        return tbUserMapper.searchUserPermissions(userId);
    }

    @Override
    public Integer login(String code) {
        //根据小程序给的授权码，从微信平台拿到用户openId,根据openId查询到用户那么就可以登录
        String openId = getOpenId(code);
        //根据openId查询用户
        TbUser user = getByOpenId(openId);
        if(ObjectUtil.isNull(user)){
            throw new EmosException("账户不存在");
        }
        // 从消息队列中接受消息，转移到消息表
        Integer id = user.getId();
        messageTask.receiveAsync(id+"");


        return user.getId();
    }

    @Override
    public TbUser searchById(Integer userId) {
        LambdaQueryWrapper<TbUser> queryWrapper = new LambdaQueryWrapper<TbUser>().eq(TbUser::getStatus, 1);
        queryWrapper.eq(TbUser::getId,userId);
        TbUser user = this.getOne(queryWrapper);
        return user;
    }

    @Override
    public String searchHiredate(Integer userId) {
        TbUser tbUser = this.searchById(userId);
        String res = DateUtil.format(tbUser.getHiredate(), "yyyy-MM-dd");
        return res;
    }

    @Override
    public HashMap searchUserSummary(int userId) {
        HashMap map=tbUserMapper.searchUserSummary(userId);
        return map;
    }

    @Override
    public ArrayList<HashMap> searchUserGroupByDept(String keyword) {
        //查询员工
        ArrayList<HashMap> list_1=deptMapper.searchDeptMembers(keyword);
        //查询部门
        ArrayList<HashMap> list_2=tbUserMapper.searchUserGroupByDept(keyword);
        //组合数据封装返回
        for(HashMap map_1:list_1){
            long deptId=(Long)map_1.get("id");
            ArrayList members=new ArrayList();
            for(HashMap map_2:list_2){
                long id=(Long) map_2.get("deptId");
                if(deptId==id){
                    members.add(map_2);
                }
            }
            map_1.put("members",members);
        }
        return list_1;





    }

    @Override
    public ArrayList searchMembers(List param) {
        ArrayList<HashMap> list=tbUserMapper.searchMembers(param);
        return list;
    }


}




